package com.example.web.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.web.SysConst;
import com.example.web.dto.*;
import com.example.web.dto.query.*;
import com.example.web.entity.*;
import com.example.web.mapper.*;
import com.example.web.service.*;
import com.example.web.tools.dto.*;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import lombok.SneakyThrows;
import com.example.web.tools.*;
/**
 * 私聊功能实现类
 */
@Service
public class WechatServiceImpl extends ServiceImpl<WechatMapper, Wechat> implements WechatService {

	 /**
     * 操作数据库AppUser表mapper对象
     */
    @Autowired
    private AppUserMapper _AppUserMapper;
    /**
     * 操作数据库的Wechat表mapper对象
     */
    @Autowired
    private WechatMapper _WechatMpper;

 			
    @Autowired
    private WeChatListMapper _WeChatListMapper;                        
			
 			
			
 			
			
 			
    @Autowired
    private GoodMapper _GoodMapper;                        
			

    /**
     * 私聊分页查询
     */
    @SneakyThrows
    @Override
    public PagedResult<WechatDto> List(WechatPagedInput input) {

      
        //声明一个支持私聊查询的(拉姆达)表达式
        LambdaQueryWrapper<Wechat> queryWrapper = Wrappers.<Wechat>lambdaQuery()
                .eq(input.getId()!=null&&input.getId()!=0,Wechat::getId,input.getId())
                .eq(input.getCreatorId()!=null,Wechat::getCreatorId,input.getCreatorId());
      
     	 //如果前端搜索传入WechatListId不为空,则进行精确查询
        if(input.getWechatListId()!=null) {
            queryWrapper=queryWrapper.eq(Wechat::getWechatListId,input.getWechatListId());
       	 }
     	 //如果前端搜索传入ReceiveUserId不为空,则进行精确查询
        if(input.getReceiveUserId()!=null) {
            queryWrapper=queryWrapper.eq(Wechat::getReceiveUserId,input.getReceiveUserId());
       	 }
     	 //如果前端传入了SendTime时间范围,则进行时间范围搜索
        if(input.getSendTimeRange()!=null&&input.getSendTimeRange().stream().count()>1)
        {
            queryWrapper=queryWrapper.lt(Wechat::getSendTime,input.getSendTimeRange().get(1));
            queryWrapper=queryWrapper.gt(Wechat::getSendTime,input.getSendTimeRange().get(0));
        }
     	 //如果前端搜索传入RelativeGoodId不为空,则进行精确查询
        if(input.getRelativeGoodId()!=null) {
            queryWrapper=queryWrapper.eq(Wechat::getRelativeGoodId,input.getRelativeGoodId());
       	 }
     	 //如果前端搜索传入SendUserId不为空,则进行精确查询
        if(input.getSendUserId()!=null) {
            queryWrapper=queryWrapper.eq(Wechat::getSendUserId,input.getSendUserId());
       	 }
      
        //按创建时间从大到小排序 最新的显示在最前面
        queryWrapper=queryWrapper.orderByDesc(Wechat::getCreationTime);
        //构建一个分页查询的model
        Page<Wechat> page = new Page<>(input.getPage(), input.getLimit());
          
   
         //从数据库进行分页查询获取私聊数据
        IPage<Wechat> pageRecords= _WechatMpper.selectPage(page, queryWrapper);

        //获取所有满足条件的数据行数
        Long totalCount= _WechatMpper.selectCount(queryWrapper);

        //把Wechat实体转换成Wechat传输模型
        List<WechatDto> items= Extension.copyBeanList(pageRecords.getRecords(),WechatDto.class);
        for (WechatDto item : items) {
          
          //查询出关联的创建用户信息
            AppUserDto  CreatorAppUserDTO=new AppUserDto();
            AppUser  CreatorAppUserEntity= _AppUserMapper.selectOne(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getId,item.getCreatorId()));
           if(CreatorAppUserEntity!=null) {
                BeanUtils.copyProperties(CreatorAppUserDTO, CreatorAppUserEntity);
                item.setCreatorAppUserDto(CreatorAppUserDTO);
            }  
         
           
          	            
           //查询出关联的WeChatList表信息
           WeChatListDto WechatListDTO = new WeChatListDto();        
            WeChatList  WechatListEntity= _WeChatListMapper.selectOne(Wrappers.<WeChatList>lambdaQuery().eq(WeChatList::getId,item.getWechatListId()));
           if(WechatListEntity!=null) {  
          BeanUtils.copyProperties(WechatListDTO,WechatListEntity);
            item.setWechatListDto(WechatListDTO); 
           }
          
           
          	            
           //查询出关联的AppUser表信息
           AppUserDto ReceiveUserDTO = new AppUserDto();        
            AppUser  ReceiveUserEntity= _AppUserMapper.selectOne(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getId,item.getReceiveUserId()));
           if(ReceiveUserEntity!=null) {  
          BeanUtils.copyProperties(ReceiveUserDTO,ReceiveUserEntity);
            item.setReceiveUserDto(ReceiveUserDTO); 
           }
          
           
          	            
           //查询出关联的AppUser表信息
           AppUserDto SendUserDTO = new AppUserDto();        
            AppUser  SendUserEntity= _AppUserMapper.selectOne(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getId,item.getSendUserId()));
           if(SendUserEntity!=null) {  
          BeanUtils.copyProperties(SendUserDTO,SendUserEntity);
            item.setSendUserDto(SendUserDTO); 
           }
          
           
          	            
           //查询出关联的Good表信息
           GoodDto RelativeGoodDTO = new GoodDto();        
            Good  RelativeGoodEntity= _GoodMapper.selectOne(Wrappers.<Good>lambdaQuery().eq(Good::getId,item.getRelativeGoodId()));
           if(RelativeGoodEntity!=null) {  
          BeanUtils.copyProperties(RelativeGoodDTO,RelativeGoodEntity);
            item.setRelativeGoodDto(RelativeGoodDTO); 
           }
          
        }
      
        //返回一个分页结构给前端
        return PagedResult.GetInstance(items,totalCount);

    }
  
    /**
     * 单个私聊查询
     */
    @SneakyThrows
    @Override
    public WechatDto Get(WechatPagedInput input) {
       if(input.getId()==null)
        {
            return new WechatDto();
        }
        PagedResult<WechatDto>  pagedResult =List(input);
        return pagedResult.getTotalCount()>0?pagedResult.getItems().stream().findFirst().get():new WechatDto();
    }

    /**
     * 得到2个人之间的聊天记录
     * @param input
     * @return
     */
    @SneakyThrows
    @Override
    public List<WechatDto> GetMyWchat(WechatDto input){
      //得到我和它聊天记录
        List<Wechat> myWchat = _WechatMpper.selectList(Wrappers.<Wechat>lambdaQuery().eq(Wechat::getSendUserId, input.getSendUserId()).eq(Wechat::getReceiveUserId, input.getReceiveUserId())).stream().toList();
        //得到它和我聊天记录
        List<Wechat> taWchat = _WechatMpper.selectList(Wrappers.<Wechat>lambdaQuery().eq(Wechat::getSendUserId, input.getReceiveUserId()).eq(Wechat::getReceiveUserId, input.getSendUserId())).stream().toList();
        //把2个人的聊天记录合并
        List<Wechat> allWchat = new ArrayList<>();
        allWchat.addAll(myWchat);
        allWchat.addAll(taWchat);
        //按照时间排序
        allWchat.sort((x,y)->x.getSendTime().compareTo(y.getSendTime()));
        //把聊天记录转换成传输模型
        List<WechatDto> items= Extension.copyBeanList(allWchat,WechatDto.class);
        for (WechatDto item : items) {

            //查询出关联的商品
            GoodDto  GoodDTO=new GoodDto();
            Good  GoodEntity= _GoodMapper.selectOne(Wrappers.<Good>lambdaQuery().eq(Good::getId,item.getRelativeGoodId()));
            if(GoodEntity!=null) {
                BeanUtils.copyProperties(GoodDTO, GoodEntity);
                item.setRelativeGoodDto(GoodDTO);
            }

      }
        return items;
    }

    /**
     *私聊创建或者修改
     */
    @SneakyThrows
    @Override
    public WechatDto CreateOrEdit(WechatDto input) {

        //先判断双方聊天列表是否都有对方
        List<WeChatList> list = _WeChatListMapper.selectList(Wrappers.<WeChatList>lambdaQuery().eq(WeChatList::getBelongUserId, input.getSendUserId()).eq(WeChatList::getReceiveUserId, input.getReceiveUserId())).stream().toList();
        //第一次聊天 把2个人都拉入到聊天信息列表中
        if(list.stream().count()==0)
        {
            WeChatList myChatList = new WeChatList();
            myChatList.setBelongUserId(input.getSendUserId());
            myChatList.setReceiveUserId(input.getReceiveUserId());
            myChatList.setLastMessage(input.getMessage());
            myChatList.setIsRead(Boolean.FALSE);
            myChatList.setLastTime(LocalDateTime.now());
            _WeChatListMapper.insert(myChatList);


            WeChatList taChatList = new WeChatList();
            taChatList.setBelongUserId(input.getReceiveUserId());
            taChatList.setReceiveUserId(input.getSendUserId());
            taChatList.setLastMessage(input.getMessage());
            taChatList.setIsRead(Boolean.FALSE);
            taChatList.setLastTime(LocalDateTime.now());
            _WeChatListMapper.insert(taChatList);

        }

        //声明一个私聊实体
        Wechat Wechat = new Wechat();

        Wechat.setIsRead(Boolean.FALSE);
        Wechat.setSendUserId(input.getSendUserId());
        Wechat.setReceiveUserId(input.getReceiveUserId());
        Wechat.setMessage(input.getMessage());
        Wechat.setSendTime(LocalDateTime.now());
        Wechat.setRelativeGoodId(input.getRelativeGoodId());


        //把刚刚写的信息同步到我的聊天列表中
        WeChatList myChatList = _WeChatListMapper.selectOne(Wrappers.<WeChatList>lambdaQuery().eq(WeChatList::getBelongUserId, input.getSendUserId()).eq(WeChatList::getReceiveUserId, input.getReceiveUserId()));
        myChatList.setLastTime(LocalDateTime.now());
        myChatList.setLastMessage(input.getMessage());
        _WeChatListMapper.updateById(myChatList);
        //把刚刚写的信息同步到它的聊天列表中
        WeChatList taChatList = _WeChatListMapper.selectOne(Wrappers.<WeChatList>lambdaQuery().eq(WeChatList::getBelongUserId, input.getReceiveUserId()).eq(WeChatList::getReceiveUserId, input.getSendUserId()));
        taChatList.setLastTime(LocalDateTime.now());
        taChatList.setLastMessage(input.getMessage());
        _WeChatListMapper.updateById(taChatList);


        //调用数据库的增加或者修改方法
        saveOrUpdate(Wechat);
        //定义一个返回给前端的私聊传输模型
        WechatDto WechatDto=new WechatDto();

        //同理把操作的私聊实体拷贝给私聊传输模型
        BeanUtils.copyProperties(WechatDto,Wechat);

        //把传输模型返回给前端
        return WechatDto;
    }



}
